<template>
  <div class="action-bar d-flex a-center pd-lr30">
    <!-- 前进后退 -->
    <div class="btn-list d-flex pd-r35">
      <div
        class="pointer mr-r60"
        @click="store.commit('prevLog')"
        :class="{ disabled: logs.isLogNull() || logs.isPositionStart() }"
      >
        <el-icon size="20px"><ArrowLeft /></el-icon>
      </div>
      <div
        class="pointer"
        @click="store.commit('nextLog')"
        :class="{ disabled: logs.isLogNull() || logs.isPositionEnd() }"
      >
        <el-icon size="20px"><ArrowRight /></el-icon>
      </div>
    </div>

    <el-popover :visible="visible" placement="bottom" width="401px">
      <div class="d-flex search-popover">
        <div class="flex-1">
          <div class="title pd-b9 pd-l15">热门</div>
          <div class="box">
            <el-skeleton class="pd-r12 pd-t5" :loading="loading" animated>
              <template #template>
                <el-skeleton :rows="7" />
              </template>
              <template #default>
                <div
                  class="popover-item d-flex"
                  v-for="(item, index) in hotSearchList"
                  :key="index"
                  @click="closePopover(startSearch(item.name))"
                >
                  <div class="flex-1 text-ellipsis pd-r5">{{ item.name }}</div>
                  <div>{{ item.count }}</div>
                </div>
              </template>
            </el-skeleton>
          </div>
        </div>
        <div class="flex-1">
          <div class="title pd-b9 pd-l15 d-flex j-sb">
            <span>搜索历史</span>
            <span class="clear music-hover font-13" @click="clearHistory">清空</span>
          </div>
          <div class="box">
            <div
              class="popover-item text-ellipsis"
              v-for="item in get('searchHistory')[userId.toString()]"
              :key="item"
              @click="closePopover(startSearch(item))"
            >
              {{ item }}
            </div>
          </div>
        </div>
      </div>
      <template #reference>
        <el-input
          @click="openPopover(initHotSearch())"
          ref="buttonRef"
          v-model="searchKey"
          class="search-class"
          placeholder="搜索音乐"
          @keyup.enter="startSearch(searchKey)"
        >
          <template #suffix>
            <el-icon class="pointer" @click="startSearch(searchKey)"><Search /></el-icon>
          </template>
        </el-input>
      </template>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, ComputedRef, inject } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { useStore } from 'vuex'
  import bus from '@/utils/bus'
  import Logs from '@/utils/logs'
  import { get, set } from '@/utils/db'
  import { addHistory, getHotSearch } from '@/api/search'
  import handlePopover from '@/hooks/usePopover'
  const { visible, openPopover, closePopover } = handlePopover()

  // eslint-disable-next-line no-undef
  defineOptions({
    name: 'ActionBar'
  })
  const loading = ref(false)
  const hotSearchList = ref<any>([])
  const initHotSearch = () => {
    loading.value = true
    getHotSearch().then((res: any) => {
      hotSearchList.value = res
      loading.value = false
    })
  }
  // 前进后退
  const store = useStore()
  const logs: ComputedRef<Logs> = computed(() => store.state.logs)

  // 搜索框
  const searchKey = ref<string>('')
  let userId = store.state.userInfo.userId
  const jumpSeachPage = inject('jumpSeachPage') as (val: string) => string

  const startSearch = (val: string) => {
    if (!val) {
      ElMessage({ message: '请输入要搜索的内容' })
      return
    }
    searchKey.value = val
    bus.emit('resetMenu')
    handleHistory(val)
    visible.value = false
    jumpSeachPage(val)
  }
  /**
   * 搜索历史
   * {
   *    userId: []   // 栈,先进后出,最多十条
   * }
   */
  const handleHistory = (val: string) => {
    if (!userId) userId = store.state.userInfo.userId
    userId = userId.toString()
    // 1.存到后台
    addHistory({ userId, searchName: val })
    // 2.从本地中取
    const historyData = get('searchHistory')
    // 3.没有则初始化
    if (!historyData || !historyData[userId]) {
      set('searchHistory', { [userId]: [val] })
      return
    }

    // 4.有
    if (historyData[userId].includes(val)) {
      if (historyData[userId].length >= 10) {
        // 4.1改变顺序
        historyData[userId].splice(
          historyData[userId].findIndex((item: string) => item === val),
          1
        )
        historyData[userId].unshift(val)
      }
    } else {
      // 4.2追加
      historyData[userId].unshift(val)
    }

    // 5.最多只能有10条,超出则从尾部开始剔除(栈,先进后出)
    if (historyData[userId].length > 10) {
      historyData[userId].pop()
    }
    // 6.存进去
    set('searchHistory', historyData)
  }

  // 清空历史
  const clearHistory = () => {
    const historyData = get('searchHistory')
    if (historyData || historyData[userId]) {
      set('searchHistory', { [userId]: [] })
    }
  }
</script>

<style lang="scss" scoped>
  .action-bar {
    height: $menuLogoHeight;
    .btn-list {
      & > div {
        width: 30px;
        height: 20px;
        text-align: center;
        &:hover {
          color: #1ece9c;
        }
        &.disabled {
          pointer-events: none;
          color: #a8abb2;
        }
      }
    }
    .search-class {
      width: 400px;
      :deep(.el-input__wrapper) {
        border-radius: 20px;
        &.is-focus {
          box-shadow: 0 0 0 1px $musicColor inset;
        }
        &:hover {
          box-shadow: 0 0 0 1px $musicColor inset;
        }
      }
    }
  }
  .search-popover {
    border-bottom: 1px solid rgb(237, 238, 238);
    & > div:first-of-type {
      border-right: 1px solid rgb(237, 238, 238);
    }

    .title {
      border-bottom: 1px solid rgb(237, 238, 238);
      .clear {
        color: rgb(128, 128, 128);
      }
    }
    .box {
      height: 300px;
      .popover-item {
        width: 187px;
        height: 30px;
        line-height: 30px;
        padding: 0 15px;
        cursor: pointer;
        &:hover {
          background-color: rgb(243, 243, 243);
        }
      }
    }
  }
</style>
